
from web.controllers.api import route_api
from  flask import request,jsonify,g
from common.models.food.Food import Food
from common.models.member.MemberCart import MemberCart
from common.libs.member.CartService import CartService
from common.libs.Helper import selectFilterObj,getDictFilterField
from common.libs.UrlManager import UrlManager
from application import app,db
import json

@route_api.route("/cart/index")
def cartIndex():
    resp = {'code': 200, 'msg': '添加购物车成功', 'data': {}}
    # 从member_cart中取出信息
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg']="获取失败，未登录"
        return jsonify(resp)
    # 根据id取出MemberCart中的所有信息
    cart_list =MemberCart.query.filter_by(member_id = member_info.id).all()
    # 取出信息后进行统一展示
    # 格式化数据
    data_cart_list =[]
    if cart_list:
    #     从selectFilterObj获取food_id
        food_ids =selectFilterObj(cart_list,"food_id")
    #     得到mapping信息：select_filed.in_( id_list )
    # 在Food表中查询id字段等于food_ids中的值，key值是id=>可以得到map结果集方便使用(map有key，方便取值)
        food_map = getDictFilterField(Food,Food.id,"id",food_ids)
        for item in cart_list:
            # 取出mapping信息
            tmp_food_info =food_map[item.food_id]
            tmp_data ={
                "id":item.id,
                "number": item.quantity,
                "food_id":item.food_id,
                "name":tmp_food_info.name,
                "price":str(tmp_food_info.price),
                "pic_url":UrlManager.buildImageUrl(tmp_food_info.main_image),
                "active":True
            }
            data_cart_list.append(tmp_data)
    # 将结果集统一返回到前台
    resp['data']['list'] = data_cart_list
    return jsonify(resp)

'''
添加东西到购物车中
'''
@route_api.route("/cart/set", methods=["POST","GET"])
def setCart():
    resp = {'code': 200, 'msg': '添加购物车成功~', 'data': {}}
    req = request.values
    food_id = int(req['id']) if 'id' in req else 0
    number = int(req['number']) if 'number' in req else 0
    if food_id < 1 :
        resp['code'] = -1
        resp['msg'] = "添加购物车失败food_id~~"
        return jsonify(resp)
    if number < 1:
        resp['code'] = -1
        resp['msg'] = "添加购物车失败number~~"
        return jsonify(resp)
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "添加购物车失败-2~~"
        return jsonify(resp)

    food_info = Food.query.filter_by( id =  food_id ).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "添加购物车失败-3~~"
        return jsonify(resp)

    if food_info.stock < number:
        resp['code'] = -1
        resp['msg'] = "添加购物车失败,库存不足~~"
        return jsonify(resp)

    ret =  CartService.setItems( member_id=member_info.id,food_id = food_info.id,number = number )
    if not ret:
        resp['code'] = -1
        resp['msg'] = "添加购物车失败-4~~"
        return jsonify(resp)
    return jsonify(resp)

@route_api.route("/cart/del", methods=["POST"])
def delCart():
    resp = {'code': 200, 'msg': '添加购物车成功~', 'data': {}}
    req = request.values
    params_goods = req['goods'] if 'goods' in req else None

    items = []
    if params_goods:
        items = json.loads(params_goods)
    if not items or len( items ) < 1:
        return jsonify(resp)

    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "删除购物车失败-1~~"
        return jsonify(resp)

    ret = CartService.deleteItem( member_id = member_info.id, items = items )
    if not ret:
        resp['code'] = -1
        resp['msg'] = "删除购物车失败-2~~"
        return jsonify(resp)
    return jsonify(resp)